package com.ray.ba.starter.security.jwt.security;


import cn.hutool.core.util.ObjectUtil;
import com.ray.ba.starter.security.jwt.constant.SecurityConstant;
import com.ray.ba.starter.security.jwt.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 * Created by macro on 2018/4/26.
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        // 解析token
        JwtUser userDetail = jwtTokenUtil.getUserFromToken(request);
        if (ObjectUtil.isNotNull(userDetail)  && SecurityContextHolder.getContext().getAuthentication() == null){
            if(userDetailsService instanceof  JwtUserDetailsServiceImpl){
                // 默认的 JwtUserDetailsServiceImpl 类型，表示本地数据库中不存储存储密码，通常是需要向CAS发起请求进行认证。此时是直接解析token,获取用户名来确定用户身份
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetail.getUsername(), SecurityConstant.NO_PASSWORD_RAW);
                authenticationToken.setDetails(userDetail);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }else{
                // 表示从数据库中获取UserDetails，然后存入 SecurityContext
                UserDetails userDetails = userDetailsService.loadUserByUsername(userDetail.getUsername());
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, SecurityConstant.NO_PASSWORD_RAW, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);

    }
}
